import { createElement, useEffect, useState } from 'rax';
import View from 'rax-view';
import Text from 'rax-text';
import Image from 'rax-image';
import {
	getStorageSync,
} from '@/utils/util';
import cloud from '@tbmp/mp-cloud-sdk';
cloud.init({
  env: 'test',
})
import './index.css';

const ModalTemplate = (props) => {
  const [canSubmit, setCanSubmit] = useState(true);
  const [suggestion, setSuggestion] = useState('');
  const [result, setResult] = useState({});
  let {
    showTemmplate,
  } = props;
  
  const [errorsList] = useState([
    {
      id: 0,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_side.png',
      name: '侧面'
    },
    {
      id: 1,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_occlusion.png',
      name: '有遮挡'
    },
    {
      id: 2,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_dark.png',
      name: '光线暗'
    },
    {
      id: 3,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_vague.png',
      name: '模糊'
    }
  ]);

  const takePhoto = () => {
    my.navigateTo({
      url: '/pages/photo/index'
    })
  }

  useEffect(()=>{
    if (suggestion && result) {
      if(result.Code == 500) {
        my.showToast({
          content: '仅支持 JPG, PNG, GIF, BMP or WebP格式照片',
          type: 'none',
          duration: 2000,
        });
        return;
      } else {
        if (result.error) {
          my.navigateTo({
            url: `/pages/photo/index?url=${result.apFilePaths}&isError=1&error=${result.error}&suggestion=${suggestion}`
          });
        } else {
          my.navigateTo({
            url: `/pages/photo/index?url=${result.url}&suggestion=${suggestion}&isError=0`
          });
        }
      }
    }
  }, [suggestion, result]);

  const onChooseImgs = async () => {
    if (canSubmit) {
      setCanSubmit(false);
      my.chooseImage({
        count: 1,
        sourceType: ['album'],
        success: images => {
          try{
            cloud.file.uploadFile({
              filePath: images.apFilePaths[0],  
              fileType: 'image',  
              fileName: 'file',
              formData: {
                file: images.apFilePaths[0], 
              },
              header: {
                'token': getStorageSync('token'),
                'user_type': 'taobao'
              },
            }).then((response) => {
              console.log('response', response);
              let {
                fileId,
                fileName,
                url
              } = response
              my.tb.imgRisk({
                data:{
                  cloudFileId: fileId
                },  
                success(res) {
                  console.log('res', res.data.result.suggestion);  
                  setSuggestion(res.data.result.suggestion)
                },  
                fail() {
                  my.alert({ title: '检查失败' });
                }, 
              });
            })
            my.uploadFile({
              url: `https://jala-test-api.sndaurl.cn/v1/user/archives/upload`,
              filePath: images.apFilePaths[0],
              fileType: 'image',
              fileName: 'file',
              formData: {
                file: images.apFilePaths[0],
              },
              header: {
                'token': getStorageSync('token'),
                'user_type': 'taobao'
              },
              success: function (response) {
                let data = JSON.parse(response.data);
                data.apFilePaths = images.apFilePaths[0]; 
                setResult(data);
                my.hideLoading({});
                setCanSubmit(true);
              },
              fail: function (res) {
              }
            });
          } catch(e) {
            // my.alert({
            //     content: 'error ' + e.message  
            // });  
            console.log(e.message);
          }
        },
        fail: function (res) {
          setCanSubmit(true);
        }
      })
    }
  }

  return (
    <View 
      className='maskView'
      onClick={()=>{
        props.onClose && props.onClose()
      }}
    >
      <View
        onClick={(e)=>{
          e.stopPropagation();
        }}
        className='modal_template'
      >
        <View className='modal_template_title'>
          添加一张正面照片
          <Image
            source={{
              uri: 'https://jala-test-images.sndaurl.cn/images/closeIcon.png'
            }}
            className='modal_template_title_icon'
            onClick={()=>{props.onClose && props.onClose()}}
            mode='aspectFill'
          />
        </View>
        <View className='modal_template_main'>
          <Image
            source={{
              uri: 'https://jala-test-images.sndaurl.cn/images/demo.png'
            }}
            className='modal_template_main_demo'
            mode='aspectFill'
          />
          <View className='modal_template_main_tip'>
            <Image
              source={{
                uri: 'https://jala-test-images.sndaurl.cn/images/checkmark.png'
              }}
              className='modal_template_main_tip_icon'
              mode='aspectFill'
            />
            五官清晰的正面
          </View>
          <View className='modal_template_main_errors'>
            {
              errorsList.map(item=>
                <View className='modal_template_main_errors_item' key={item.id}>
                  <Image
                    source={{
                      uri: item.icon
                    }}
                    mode='aspectFill'
                    className='modal_template_main_errors_item_demo'
                  />
                  <View className='modal_template_main_errors_item_tip'>
                    <Image
                      source={{
                        uri: 'https://jala-test-images.sndaurl.cn/images/closeBg.png'
                      }}
                      className='modal_template_main_errors_item_tip_icon'
                      mode='aspectFill'
                    />
                    {item.name}
                  </View>
                </View>
              )
            }
          </View>
        </View>
        <View className='modal_template_main_line'></View>
        <View className='modal_template_main_tips'>
          <View className='modal_template_main_tips_title'>建议上传照片满足上方提示，不然效果可能会打折哦</View>
          <View className='modal_template_main_tips_actions'>
            <View className='modal_template_main_tips_actions_item' onClick={()=>{takePhoto()}}>
              <Image
                source={{
                  uri: 'https://jala-test-images.sndaurl.cn/images/photo.png'
                }}
                mode='aspectFill'
                className='modal_template_main_tips_actions_item_icon'
              />
              <Text className='modal_template_main_tips_actions_item_text'>拍照上传</Text>
            </View>
            <View className='modal_template_main_tips_actions_item' onClick={()=>{onChooseImgs()}}>
              <Image
                source={{
                  uri: 'https://jala-test-images.sndaurl.cn/images/album.png'
                }}
                mode='aspectFill'
                className='modal_template_main_tips_actions_item_icon'
              />
              <Text className='modal_template_main_tips_actions_item_text'>从相册选择</Text>
            </View>
          </View>
        </View>
      </View>
    </View>
  )
}

export default ModalTemplate;
